package com.tuling.netty.handler;

import com.tuling.netty.command.Cmd;
import com.tuling.netty.command.CmdProtocol;
import com.tuling.protostuff.ProtostuffUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

public class CommandEncoder extends MessageToByteEncoder<Cmd> {
    @Override
    protected void encode(ChannelHandlerContext ctx, Cmd cmd, ByteBuf out) throws Exception {
        // /----/----------------------/
        // 1、4byte 标识 指令对象转byte数组长度 2、指令对象数据
        CmdProtocol protocol = new CmdProtocol();
        protocol.setCmd(cmd);

        byte[] bytes = ProtostuffUtils.serialize(protocol);
        out.writeInt(bytes.length);
        out.writeBytes(bytes);
    }
}